package com.ficus.road.maintain.core.infrastructure.mongo.increment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/**
 * 用mongo的原子操作,实现自增id
 *
 * @author sdfu
 * @data 2019-03-21 13:25
 * @description
 */
@Component
public class SaveEventListener extends AbstractMongoEventListener<Object> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        final Object source = event.getSource();
        ReflectionUtils.doWithFields(source.getClass(), field -> {
            ReflectionUtils.makeAccessible(field);
            // 如果字段添加了AutoIncrement注解
            if (field.isAnnotationPresent(AutoIncrement.class) && field.get(source) == null) {
                // 设置自增ID
                field.set(source, getNextAutoId(source.getClass().getSimpleName()));
            }
        });
    }

    // 获取下一个自增ID
    private Integer getNextAutoId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("seqId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        SequenceId seq = mongoTemplate
                .findAndModify(query, update, options, SequenceId.class);
        return seq.getSeqId();
    }

}